"""
Room service for managing meeting rooms.
"""
from typing import List, Optional
from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from uuid import UUID
from app.models.room import Room
from app.schemas.room import RoomCreate, RoomUpdate


def get_room(db: Session, room_id: UUID) -> Optional[Room]:
    """Get a room by ID."""
    return db.query(Room).filter(Room.id == room_id).first()


def get_room_by_name(db: Session, name: str) -> Optional[Room]:
    """Get a room by name."""
    return db.query(Room).filter(Room.name == name).first()


def get_rooms(db: Session, skip: int = 0, limit: int = 100) -> List[Room]:
    """
    Get all rooms.
    
    Args:
        db: Database session
        skip: Number of records to skip
        limit: Maximum number of records to return
        
    Returns:
        List of rooms
    """
    return db.query(Room).offset(skip).limit(limit).all()


def create_room(db: Session, room: RoomCreate) -> Room:
    """
    Create a new meeting room.
    
    Args:
        db: Database session
        room: Room creation schema
        
    Returns:
        Created room object
    """
    # Check if room name already exists
    existing_room = get_room_by_name(db, room.name)
    if existing_room:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Room with name '{room.name}' already exists"
        )
    
    db_room = Room(**room.model_dump())
    db.add(db_room)
    db.commit()
    db.refresh(db_room)
    
    return db_room


def update_room(db: Session, room_id: UUID, room_update: RoomUpdate) -> Room:
    """
    Update room information.
    
    Args:
        db: Database session
        room_id: Room ID
        room_update: Room update schema
        
    Returns:
        Updated room object
    """
    db_room = get_room(db, room_id)
    if not db_room:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Room not found"
        )
    
    update_data = room_update.model_dump(exclude_unset=True)
    
    # Check if new name conflicts with existing room
    if "name" in update_data:
        existing_room = get_room_by_name(db, update_data["name"])
        if existing_room and existing_room.id != room_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Room with name '{update_data['name']}' already exists"
            )
    
    for field, value in update_data.items():
        setattr(db_room, field, value)
    
    db.commit()
    db.refresh(db_room)
    
    return db_room


def delete_room(db: Session, room_id: UUID) -> bool:
    """
    Delete a meeting room.
    
    Args:
        db: Database session
        room_id: Room ID
        
    Returns:
        True if deleted successfully
    """
    db_room = get_room(db, room_id)
    if not db_room:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Room not found"
        )
    
    # Check if room has active bookings
    from app.models.booking import Booking, BookingStatus
    active_bookings = db.query(Booking).filter(
        Booking.room_id == room_id,
        Booking.status.in_([BookingStatus.PENDING, BookingStatus.CONFIRMED])
    ).count()
    
    if active_bookings > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Cannot delete room with {active_bookings} active booking(s)"
        )
    
    db.delete(db_room)
    db.commit()
    
    return True
